const express = require('express');
const router = express.Router();
const { testConnection } = require('../config/db');
const { defaultCache, videoListCache, categoryCache } = require('../utils/cache');
const os = require('os');

/**
 * 健康检查端点
 */
router.get('/health', async (req, res) => {
  const health = {
    status: 'ok',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    environment: process.env.NODE_ENV || 'development'
  };

  // 检查数据库连接
  try {
    const dbConnected = await testConnection();
    health.database = dbConnected ? 'connected' : 'disconnected';
  } catch (error) {
    health.database = 'error';
    health.status = 'error';
  }

  res.status(health.status === 'ok' ? 200 : 503).json(health);
});

/**
 * 详细状态端点
 */
router.get('/status', async (req, res) => {
  const status = {
    status: 'ok',
    timestamp: new Date().toISOString(),
    system: {
      platform: os.platform(),
      arch: os.arch(),
      nodeVersion: process.version,
      uptime: process.uptime(),
      hostname: os.hostname()
    },
    memory: {
      total: os.totalmem(),
      free: os.freemem(),
      used: os.totalmem() - os.freemem(),
      usedPercentage: ((os.totalmem() - os.freemem()) / os.totalmem() * 100).toFixed(2) + '%',
      process: {
        rss: process.memoryUsage().rss,
        heapTotal: process.memoryUsage().heapTotal,
        heapUsed: process.memoryUsage().heapUsed,
        external: process.memoryUsage().external
      }
    },
    cpu: {
      cores: os.cpus().length,
      model: os.cpus()[0]?.model,
      loadAverage: os.loadavg()
    }
  };

  // 数据库状态
  try {
    const dbConnected = await testConnection();
    status.database = {
      status: dbConnected ? 'connected' : 'disconnected',
      type: 'MySQL'
    };
  } catch (error) {
    status.database = {
      status: 'error',
      error: error.message
    };
    status.status = 'degraded';
  }

  // 缓存状态
  status.cache = {
    default: defaultCache.getStats(),
    videoList: videoListCache.getStats(),
    category: categoryCache.getStats()
  };

  res.json(status);
});

/**
 * 清除缓存端点（需要管理员权限）
 */
router.post('/cache/clear', (req, res) => {
  const { cacheType } = req.body;

  try {
    switch (cacheType) {
      case 'all':
        defaultCache.clear();
        videoListCache.clear();
        categoryCache.clear();
        break;
      case 'video':
        videoListCache.clear();
        break;
      case 'category':
        categoryCache.clear();
        break;
      default:
        defaultCache.clear();
    }

    res.json({
      code: 200,
      msg: '缓存清除成功',
      timestamp: Date.now()
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      msg: '缓存清除失败',
      error: error.message,
      timestamp: Date.now()
    });
  }
});

/**
 * Ping 端点
 */
router.get('/ping', (req, res) => {
  res.json({
    message: 'pong',
    timestamp: Date.now()
  });
});

module.exports = router;

